package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.TeamMemberItemBean;
import sql.TeamMemberDao;

/**
 * Servlet implementation class EditTeamMember
 */
@WebServlet("/EditTeamMember")
public class EditTeamMember extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditTeamMember() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TeamMemberItemBean teamMemberItemBean = new TeamMemberItemBean();

		teamMemberItemBean.setName(request.getParameter("name"));
		teamMemberItemBean.setEmail(request.getParameter("email"));
		teamMemberItemBean.setPassword(request.getParameter("password"));
		
		try {
			teamMemberItemBean.setId(Integer.parseInt(request.getParameter("team-member-id")));
			
			//  if normal user, role and project are not sent as request parameters because they are grayed out 
			String role = request.getParameter("role");
			if (role != null) {
				teamMemberItemBean.setRoleId(Integer.parseInt(role));
			}
			
			String project = request.getParameter("project");
			if (project != null) {
				teamMemberItemBean.setProjectId(Integer.parseInt(project));
			}
		}
		catch (NumberFormatException e) {
			e.printStackTrace();
		}

		TeamMemberDao teamMemberDao = new TeamMemberDao();
		try {
			teamMemberDao.update(teamMemberItemBean);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		
		// return data
		PrintWriter out = response.getWriter();
		out.write(teamMemberItemBean.getJson());
	}

}
